package com.scproject.scbef.service.study.politicsactivity.impl;

import com.scproject.dto.ResponseDto;
import com.scproject.scbef.exception.ProcessException;
import com.scproject.scbef.mapper.ImgMapper;
import com.scproject.scbef.mapper.ImgRelationMapper;
import com.scproject.scbef.mapper.PoliticsBuildActivityMapper;
import com.scproject.scbef.mapper.expandmapper.PoliticsBuildActivityDetailInfoMapper;
import com.scproject.scbef.pojo.Img;
import com.scproject.scbef.pojo.ImgRelation;
import com.scproject.scbef.pojo.PoliticsBuildActivity;
import com.scproject.scbef.pojo.expandenum.ImgTypeEnum;
import com.scproject.scbef.pojo.vo.PoliticsActivitiesVo;
import com.scproject.scbef.pojo.vo.ResponseCodeEnum;
import com.scproject.scbef.service.study.politicsactivity.PoliticsActivityService;
import com.scproject.utils.FtpFileUtil;
import com.scproject.utils.JWTUtils;
import com.scproject.utils.ProcessFileUtils;
import com.scproject.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.scproject.utils.ProcessFileUtils.processFile;

/**
 * @author LNL
 * @date 2021/5/23 10:19
 */
@Service("politicsActivityService")
@Transactional
public class PoliticsActivityServiceImpl implements PoliticsActivityService {

    @Autowired
    private PoliticsBuildActivityDetailInfoMapper politicsBuildActivityDetailInfoMapper;

    @Autowired
    private ImgMapper imgMapper;

    @Autowired
    private ImgRelationMapper imgRelationMapper;

    @Autowired
    private PoliticsBuildActivityMapper politicsBuildActivityMapper;

    @Override
    public ResponseDto getAllActivities() {
        ResponseDto responseDto = null;
        List<PoliticsActivitiesVo> activities = politicsBuildActivityDetailInfoMapper.getAllActivities(ImgTypeEnum.POLITICS_ACTIVITY.toString());
        Optional<List<PoliticsActivitiesVo>> optionalList = Optional.ofNullable(activities);
        if (optionalList.isPresent()) {
            responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(), "党建活动信息", activities);
        } else {
            responseDto = new ResponseDto(ResponseCodeEnum.ERROR.toString(), "信息获取失败");
        }
        return responseDto;
    }

    @Override
    public ResponseDto deleteActivity(String id) {
        ResponseDto responseDto = null;
        //逻辑：删除活动的同时，将图片关联一起删除，并且删除项目中保留的图片
        //通过活动id查询出img的id
        ImgRelation imgRelation = imgRelationMapper.selectByRelationId(id);
        //通过imgId查询
        Img img = imgMapper.selectByPrimaryKey(imgRelation.getImgId());
        //删除图片信息
        int isDeleteImg = imgMapper.deleteByPrimaryKey(img.getId());
        //删除图片关联信息
        int isDeleteImgRelation = imgRelationMapper.deleteByRelationId(id, ImgTypeEnum.POLITICS_ACTIVITY.toString());
        //删除活动
        int isDeleteActivity = politicsBuildActivityMapper.deleteByPrimaryKey(id);
        if (isDeleteActivity > 0 ) {
            //删除本地图片
            responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(), "删除成功");
        } else {
            throw new ProcessException("删除失败");
        }
        return responseDto;
    }

    @Override
    public ResponseDto insertActivity(MultipartHttpServletRequest request) {
        ResponseDto responseDto = null;
        try {
            //获取当前用户信息
            Map<String, String> userInfo = JWTUtils.getInfo(request.getHeader("token"));
            //处理时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //包含title、content、publishTime、endTime这三个信息
            Map<String, String[]> newsData = request.getParameterMap();
            //处理逻辑，如果数据不为空，那么创建校园新闻+图片关联
            PoliticsBuildActivity politicsBuildActivity = new PoliticsBuildActivity();
            politicsBuildActivity.setId(UUIDUtils.getUUID());
            politicsBuildActivity.setTitle(newsData.get("title")[0] == null ? "" : newsData.get("title")[0]);
            politicsBuildActivity.setContent(newsData.get("content")[0] == null ? "" : newsData.get("content")[0]);
            politicsBuildActivity.setIsOpen((byte) 1);

            politicsBuildActivity.setPublishTime(sdf.parse(newsData.get("publishTime")[0]) == null ?
                    new Date() :
                    sdf.parse(newsData.get("publishTime")[0]));
            politicsBuildActivity.setEndTime(sdf.parse(newsData.get("endTime")[0]) == null ?
                    new Date() :
                    sdf.parse(newsData.get("endTime")[0]));
            politicsBuildActivity.setCreateUser(userInfo.get("userId"));
            politicsBuildActivity.setCreateTime(new Date());

            int isInsertActivity = politicsBuildActivityMapper.insertSelective(politicsBuildActivity);

            if (isInsertActivity > 0) {
                List<MultipartFile> files = request.getFiles("file_transfer");
                for (MultipartFile file : files) {
                    Map<String, String> fileData = ProcessFileUtils.processFile(file);
                    //将图片存放到数据库中
                    Img img = new Img();
                    img.setId(UUIDUtils.getUUID());
                    img.setName(fileData.get("fileName"));
                    img.setPath(fileData.get("filePath"));

                    ImgRelation imgRelation = new ImgRelation();
                    imgRelation.setId(UUIDUtils.getUUID());
                    imgRelation.setImgId(img.getId());
                    imgRelation.setRelationId(politicsBuildActivity.getId());
                    imgRelation.setType(ImgTypeEnum.POLITICS_ACTIVITY.toString());

                    int isInsertImg = imgMapper.insertSelective(img);
                    int isInsertImgRelation = imgRelationMapper.insertSelective(imgRelation);

                    if(isInsertImg > 0 && isInsertImgRelation > 0) {
                        responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(), "添加成功");
                    }else {
                        throw new ProcessException("添加失败");
                    }
                }
            } else {
                throw new ProcessException("添加失败");
            }
        } catch (Exception e) {
            throw new ProcessException("时间格式或字段异常，请联系管理员");
        }
        return responseDto;
    }

    @Override
    public ResponseDto updateActivity(PoliticsBuildActivity politicsBuildActivity, HttpServletRequest request) {
        ResponseDto responseDto = null;
        Map<String, String> userInfo = JWTUtils.getInfo(request.getHeader("token"));
        politicsBuildActivity.setEditUser(userInfo.get("userId"));
        politicsBuildActivity.setEditTime(new Date());

        //处理修改
        try {
            int isUpdate = politicsBuildActivityMapper.updateByPrimaryKeySelective(politicsBuildActivity);
            if (isUpdate > 0) {
                responseDto = new ResponseDto(ResponseCodeEnum.SUCCESS.toString(), "更新成功");
            } else {
                throw new ProcessException("更新失败");
            }
        } catch (Exception e) {
            throw new ProcessException("更新失败");
        }
        return responseDto;
    }
}
